package org.punkgrok.flightrecorder.strutstestcase;

import org.punkgrok.flightrecorder.MethodInvocation;
import org.punkgrok.flightrecorder.ProxyBasedTestCodeBuilder;

import java.util.List;
import java.util.LinkedList;

/**
 * User: Roman Florian Zabicki III
 * Date: May 30, 2009
 * Time: 5:24:03 PM
 */
public class StrutsTestCaseBuilder extends ProxyBasedTestCodeBuilder {
	@Override
	protected String getTestMethodBody(List<MethodInvocation> invokedMethods) {
		String testMethodBody = "";
		String actionName = ((String) getInvocations("getServletPath", invokedMethods).get(0).getReturnValue());
		actionName = actionName.substring(0, actionName.indexOf(".do"));

		testMethodBody += "setRequestPathInfo(\"" + actionName + "\");\n";

		for (MethodInvocation invokedMethod : getInvocations("getParameter", invokedMethods)) {
			String parameterName = "\"" + invokedMethod.getArgs()[0] + "\"";
			String parameterValue = invokedMethod.getReturnValue() == null ? "(String)null" : "\"" + invokedMethod.getReturnValue() + "\"";
			testMethodBody += "addRequestParameter(" + parameterName + ", " + parameterValue + ");\n";
		}

		testMethodBody += "actionPerform();\n";

		return testMethodBody;
	}

	private List<MethodInvocation> getInvocations(String methodName, List<MethodInvocation> invocations) {
		List<MethodInvocation> matches = new LinkedList<MethodInvocation>();
		for (MethodInvocation invocation : invocations) {
			if(invocation.getMethodName().equals(methodName)) {
				matches.add(invocation);
			}
		}
		return matches;
	}
}
